// observable 创建被监测的对象，对象中的属性会被转换为响应式数据
// action 函数用来显式的定义 action 方法
import { observable, action } from 'mobx-miniprogram'
import { getStorage } from '@/utils/storage'
import { setStorage, removeStorage } from '@/utils/storage'

export const userStore = observable({
  // token 身份令牌
  loginInfo: getStorage('token') || '',
  // 用户信息
  userInfo: getStorage('userInfo') || {},
  
  // 定义 action
  // setToken 用来修改、更新 token
  setLoginInfo: action(function (loginInfo: any) {
    // 在调用 setToken 方法时，需要传入 token 数据进行赋值
    setStorage("loginInfo", loginInfo)
    this.loginInfo = loginInfo
  }),

  // 对用户信息进行赋值
  setUserInfo: action(function (userInfo: any) {
    setStorage("userInfo", userInfo)
    this.userInfo = userInfo
  }),
  //获取token
  getToken() {
    let user = this.loginInfo
    if (!user) {
      user = getStorage("loginInfo");
    }
    if (!user || user == null || user.token == null || user.expiresIn == null || user.cTime == null) {
      return ''
    }
    if (user.expiresIn == undefined || user.expiresIn < (Date.now() - user.cTime) / 1000) {
      this.loginInfo = {}
      this.userInfo = {}
      removeStorage("loginInfo")
      removeStorage("userInfo")
      return ''
    }
    return user.token
  }
})
